// Server API makes it possible to hook into various parts of Gridsome
// on server-side and add custom data to the GraphQL data layer.
// Learn more: https://gridsome.org/docs/server-api/

// Changes here require a server restart.
// To restart press CTRL + C in terminal and run `gridsome develop`
const axios = require('axios');
const userApi = require('./api/user');
const projApi = require('./api/project');
const gistApi = require('./api/gist');

let addFn = null;
let collections = [];
let cbs = [];

let createCollection = (name, cb) => {
  collections.push(addFn({ typeName: name }));
  cbs.push(cb);
}

let addNodes = (collection, data, i) => {
  if (data instanceof Array) {
    data.reverse().forEach(item => {
      item.files = JSON.stringify(item.files);
      collection.addNode(item);
    });
  } else {
    collection.addNode(data);
  }
}

module.exports = function (api) {
  api.loadSource(async ({ addCollection }) => {
    addFn = addCollection; // 将 addCollection 存到全局

    createCollection('UserInfo', userApi.getInfo()); // 获取用户信息
    createCollection('Projects', projApi.projects()); // 获取用户的开源仓库列表
    createCollection('Gists', gistApi.gists()); // 获取博客列表
    createCollection('Followers', userApi.followers(1)); // 获取粉丝列表
    createCollection('Following', userApi.following()); // 获取关注列表

    const result = await Promise.all(cbs);
    const newGistId = result[2].data[0].id;
    
    result.forEach((item, i) => {
      addNodes(collections[i], item.data, i);
    });

    const newgist = addCollection({typeName: 'NewGist'}); // 获取最新的博客
    const {data} = await gistApi.single(newGistId);
    data.files = JSON.stringify(data.files);
    newgist.addNode(data);
  });

  api.createPages(({ createPage }) => {
    // Use the Pages API here: https://gridsome.org/docs/pages-api/
  })
}
